<template>
  <div class="container">
    <!-- 顶部菜单 -->
    <el-menu
      class="top-layer"
      mode="horizontal"
      background-color="#1e2430"
      text-color="#617b91"
      active-text-color="#4583ff"
      :ellipsis="false"
    >
      <el-menu-item
        v-for="item in topLabels"
        :key="item.to.id"
        @click="selectTopItem(item)"
        :class="{ 'active-top': activeTop === item.to.id }"
      >
        {{ item.toName }}
      </el-menu-item>
    </el-menu>

    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 左侧二级菜单 -->
      <el-menu
        class="second-layer"
        :default-active="activeSecond"
        @select="selectSecondItem"
        text-color="#617b91"
        active-text-color="#4583ff"
      >
        <el-menu-item v-for="item in secondLayerData" :key="item.to.id" :index="item.to.id">
          {{ formatName(item.toName) }}
        </el-menu-item>
      </el-menu>

      <!-- 三级/四级内容 -->
      <div class="third-layer">
        <el-scrollbar class="scroll-container">
          <el-collapse v-model="activeFourth" accordion class="third-content">
            <!-- 搜索框 -->
            <el-input
              v-model="searchQuery"
              :placeholder="isSearchFocused ? '' : '搜索...'"
              class="search-box"
              clearable
              @focus="isSearchFocused = true"
              @blur="isSearchFocused = false"
              v-if="
                currentSecondName.startsWith('我的资源-') ||
                currentSecondName.startsWith('系统资源-')
              "
            />
            <el-button
              v-if="currentSecondName.startsWith('我的资源-')"
              type="primary"
              @click="dialogVisibleFolder = true"
              class="upload-file"
              style="margin-bottom: 10px"
            >
              新建文件夹
            </el-button>
            <el-dialog
              title="新建文件夹"
              width="500"
              v-model="dialogVisibleFolder"
              class="folder-modal"
            >
              <el-form>
                <el-form-item label="文件夹名称">
                  <el-input
                    v-model="newFolderName"
                    placeholder="请输入文件夹名称"
                    clearable
                    @keyup.enter="handleCreateFolder"
                    :ref="`folderInput`"
                    :id="`folderInput`"
                  />
                </el-form-item>
              </el-form>
              <span class="dialog-footer">
                <el-button @click="dialogVisibleFolder = false">取消</el-button>
                <el-button type="primary" @click="handleCreateFolder">创建</el-button>
              </span>
            </el-dialog>
            <template v-if="currentSecondName === '结构-节点'">
              <NodeTree />
            </template>
            <el-collapse-item
              v-for="item in filteredThirdLayerData"
              :key="item.to.id"
              :name="item.to.id"
              @click="toggleFourthLayer(item)"
              v-else
            >
              <template #title>
                <div class="third-item">
                  <!-- 高亮匹配部分 -->
                  <span v-html="highlightMatch(formatName(item.toName), searchQuery)"></span>
                  <el-icon>
                    <arrow-down />
                  </el-icon>
                </div>
              </template>

              <div class="fourth-layer">
                <!-- 上传按钮 -->
                <el-button
                  v-if="currentSecondName === '我的资源-模型'"
                  type="primary"
                  @click="dialogVisibleFold = true"
                  class="upload-file"
                  style="margin-bottom: 10px"
                >
                  上传文件
                </el-button>
                <el-button
                  v-if="currentSecondName === '系统资源-方案'"
                  type="primary"
                  class="upload-file"
                  style="margin-bottom: 10px"
                  @click="dialogVisiblePlan = true"
                >
                  新建方案
                </el-button>
                <!-- 上传文件弹窗 -->
                <el-dialog
                  :id="`modal-${item.to.id}`"
                  class="modal"
                  v-model="dialogVisibleFold"
                  align-center
                >
                  <div class="container">
                    <h2>文件上传</h2>
                    <div class="upload-box">
                      <input
                        type="file"
                        :ref="`fileInput-${item.to.id}`"
                        :id="`fileInput-${item.to.id}`"
                        accept=".fbx,.txt,.jpg"
                      />
                      <el-button @click="uploadFile(item.to.id)">上传文件</el-button>
                      <div class="progress-bar">
                        <div class="progress" :style="{ width: progress + '%' }"></div>
                      </div>
                      <div id="status" class="status">{{ statusMessage }}</div>
                    </div>
                  </div>
                </el-dialog>

                <!-- 新建方案弹窗 -->
                <el-dialog
                  title="新建方案"
                  width="500"
                  v-model="dialogVisiblePlan"
                  :id="`plan-modal-${item.to.id}`"
                  class="plan-modal"
                >
                  <el-form>
                    <el-form-item label="方案名称">
                      <el-input
                        v-model="newFolderName"
                        placeholder="请输入方案名称"
                        clearable
                        @keyup.enter="handleCreateFolder"
                        :ref="`planInput-${item.to.id}`"
                        :id="`planInput-${item.to.id}`"
                      />
                    </el-form-item>
                  </el-form>
                  <span class="dialog-footer">
                    <el-button @click="dialogVisiblePlan = false">取消</el-button>
                    <el-button type="primary" @click="handleCreatePlan(item.to.id)">创建</el-button>
                  </span>
                </el-dialog>
                <el-scrollbar class="graph-scrollbar">
                  <!-- 第四层数据展示 -->
                  <div
                    v-for="fourth in filteredFourthItems(item)"
                    :key="fourth?.to?.id"
                    class="graph-item"
                    @click="handleItemClick(fourth)"
                    :class="{ 'is-active': selectedItemId === (fourth?.to?.id || '') }"
                  >
                    <div class="item-container">
                      {{ formatName(fourth?.toName) }}

                      <el-button
                        v-if="
                          currentSecondName.startsWith('我的资源-') ||
                          currentSecondName.startsWith('系统资源-')
                        "
                        class="delete-file"
                        @click.stop="handleDeleteItem(fourth, item.to.id)"
                      >
                        删除
                      </el-button>
                    </div>
                  </div>
                </el-scrollbar>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-scrollbar>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, nextTick, getCurrentInstance, computed, watch } from 'vue';
  import { getRelationByFrom } from '/@/api/thingsborad/entity/entity';
  import {
    relationResponse,
    relationByFromParams,
  } from '/@/api/thingsborad/entity/model/entityModel';
  import { ArrowDown } from '@element-plus/icons-vue';
  import {
    ElMenu,
    ElMenuItem,
    ElScrollbar,
    ElCollapse,
    ElCollapseItem,
    ElInput,
    ElButton,
    ElDialog,
    ElForm,
    ElFormItem,
    ElMessage,
    ElIcon,
  } from 'element-plus';
  import { debounce } from 'lodash-es';
  import {
    FileService,
    uploadToServer,
    saveUploadData,
    saveDevicePlan,
    createPlan,
    createFolder,
  } from '../newleft/service/fileService';
  import { sendMessageToUnity, sendMultipleFilesToUnity } from '../newleft/service/unityService';
  import { chooseModel, FileLoadUrl } from '/@/core/communication/interface/ISendUnity';

  import { useEntityDeleter } from './store/deleteentity';
  import { useStore } from 'vuex';
  import { formatName } from '/@/views/DigitalTwin/newleft/service/formatName';
  import NodeTree from '/@/views/DigitalTwin/newleft/component/NodeTree.vue';

  const { deleteEntity } = useEntityDeleter();

  // 添加删除处理函数
  const handleDeleteItem = async (item: relationResponse, parentId: string) => {
    try {
      // 添加参数校验
      if (!item?.to?.entityType) {
        ElMessage.warning('无效的实体类型');
        return;
      }

      // 修正entityType为小写（根据后端要求）
      const fixedEntityType = item.to.entityType.toLowerCase();

      await deleteEntity(item.to.id, parentId, fixedEntityType, fourthLayerData, toggleFourthLayer);

      if (store.getters.selectedIssue === item) {
        store.commit('SET_SELECTED_ITEM_ID', '');
      }
    } catch (error) {
      console.error('删除操作异常:', error);
    }
  };

  //弹窗
  const dialogVisibleFolder = ref(false);
  const dialogVisiblePlan = ref(false);
  const dialogVisibleFold = ref(false);
  // 新增变量：记录当前第二层名称
  const currentSecondName = ref('');
  // 其他变量保持不变
  const topLabels = ref<relationResponse[]>([]);
  const secondLayerData = ref<relationResponse[]>([]);
  const thirdLayerData = reactive<Record<string, relationResponse[]>>({});
  const fourthLayerData = reactive<Record<string, relationResponse[]>>({});
  const nodeData = reactive<Record<string, relationResponse[]>>({});
  const activeTop = ref<string>('');
  const activeSecond = ref<string>('');
  const activeFourth = ref<string[]>([]);
  const newFolderName = ref('');
  const folderErrorMessage = ref('');
  // 在组件中定义响应式变量存储当前选中ID
  const selectedAssetProfileId = ref<string>('');

  const fileInputs = ref<Record<string, HTMLInputElement>>({});
  // const planInputs = ref<Record<string, HTMLInputElement>>({});
  const progress = ref(0);
  const statusMessage = ref('');
  let isProcessing = false;

  // 新增高亮方法
  const highlightMatch = (text: string, query: string) => {
    const cleanQuery = query.trim().toLowerCase();
    if (!cleanQuery) return text;

    const regex = new RegExp(`(${cleanQuery})`, 'gi');
    return text.replace(regex, '<span class="highlight">$1</span>');
  };

  // 新增搜索相关代码
  const searchQuery = ref('');
  const isSearchFocused = ref(false);
  // 模糊匹配函数
  const fuzzyMatch = (str: string, query: string) => {
    const cleanStr = str.toLowerCase().replace(/\s+/g, '');
    const cleanQuery = query.toLowerCase().replace(/\s+/g, '');
    return cleanStr.includes(cleanQuery);
  };

  // 计算过滤后的三级菜单数据
  const filteredThirdLayerData = computed(() => {
    const query = searchQuery.value.trim();
    if (!query) return thirdLayerData[activeSecond.value] || [];

    return (thirdLayerData[activeSecond.value] || []).filter((thirdItem) => {
      // 检查三级菜单名称
      const thirdNameMatch = fuzzyMatch(formatName(thirdItem.toName), query);

      // 检查对应的四级菜单
      const fourthItems = fourthLayerData[thirdItem.to.id] || [];
      const hasMatchingFourth = fourthItems.some((fourthItem) =>
        fuzzyMatch(formatName(fourthItem.toName), query),
      );

      return thirdNameMatch || hasMatchingFourth;
    });
  });

  // 过滤第四层数据的方法
  const filteredFourthItems = (thirdItem: relationResponse): relationResponse[] => {
    let data: relationResponse[] = [];

    if (currentSecondName.value === '结构-节点') {
      data = nodeData.value; // 结构-节点的特殊处理
    } else {
      data = fourthLayerData[thirdItem.to.id] || [];
    }

    if (!searchQuery.value) {
      return data;
    }

    return data.filter((fourth) => {
      const formattedName = formatName(fourth.toName);
      return formattedName.toLowerCase().includes(searchQuery.value.toLowerCase());
    });
  };

  // 新增搜索执行方法
  const executeSearch = async (query: string) => {
    // 获取所有可能匹配的三级项（包含已加载和未加载的）
    const allThirdItems = thirdLayerData[activeSecond.value] || [];

    // 分两步筛选：
    const matchedItems = allThirdItems.filter((thirdItem) => {
      // 第一步：快速筛选可能匹配项
      return (
        fuzzyMatch(formatName(thirdItem.toName), query) ||
        (fourthLayerData[thirdItem.to.id] || []).some((fourthItem) =>
          fuzzyMatch(formatName(fourthItem.toName), query),
        )
      );
    });

    // 第二步：深度加载验证
    const verifiedItems = await Promise.all(
      matchedItems.map(async (item) => {
        if (!fourthLayerData[item.to.id]?.length) {
          await toggleFourthLayer(item, true);
        }
        return item;
      }),
    );

    // 确定需要展开的项
    return verifiedItems.filter((item) =>
      (fourthLayerData[item.to.id] || []).some((fourthItem) =>
        fuzzyMatch(formatName(fourthItem.toName), query),
      ),
    );
  };

  // 修改watch监听
  watch(
    searchQuery,
    debounce(async (newVal) => {
      const query = newVal.trim().toLowerCase();
      if (!query) {
        activeFourth.value = [];
        return;
      }

      const finalMatchedItems = await executeSearch(query);
      activeFourth.value = finalMatchedItems.map((item) => item.to.id);
    }, 300),
  ); // 添加300ms防抖

  // 键盘事件监听
  /*  document.addEventListener('keydown', async function (event) {
    if (event.code === 'KeyI' && !isProcessing) {
      isProcessing = true;
      console.log('i 键被按下');
      try {
        const simulatedItem: relationResponse = {
          toName: '',
          to: {
            entityType: 'ASSET',
            id: '67fe8640-135f-11f0-9456-7394060ad530',
          },
          from: {
            entityType: 'ASSET',
            id: '',
          },
          type: '',
          typeGroup: '',
          additionalInfo: '',
          fromName: '',
        };

        // 模拟点击时的前置操作
        selectedItemId.value = simulatedItem.to.id;
        const displayName = formatName(simulatedItem.toName);
        emit('title-change', displayName);

        // 获取节点数据
        await getNodeData(simulatedItem);
        const filenames = Object.values(nodeData).flatMap((array) =>
          array.map((item) => item.toName),
        );
        console.log('发送方案节点:', filenames);
        await sendMultipleFilesToUnity(filenames);
      } catch (error) {
        console.error('I 键操作失败:', error);
      } finally {
        isProcessing = false;
      }
    }
  });*/
  onMounted(async () => {
    // 初始化逻辑保持不变
    try {
      const firstParams: relationByFromParams = {
        fromId: '4b7d2d80-5bd2-11f0-baf1-1f027592f510',
        fromType: 'ASSET',
      };
      const firstRes = await getRelationByFrom(firstParams);
      topLabels.value = firstRes;

      if (firstRes.length > 0) {
        await selectTopItem(firstRes[0]);
      }
      if (secondLayerData.value[0].toName === '系统资源-方案') {
        //系统方案那一层的第一个：系统资源-方案
        const system = secondLayerData.value[0];
        //方案文件夹那一层：方案-方案1...
        const issue = thirdLayerData[system.to.id][0];
        //方案那一层：方案1-默认方案
        const defaultIssue = fourthLayerData[issue.to.id].find(
          (item) => item.toName.indexOf('默认方案') !== -1,
        );
        //默认展开第1项
        activeFourth.value = [thirdLayerData[system.to.id][0].to.id];
        //默认选中第1项的第一个
        await handleItemClick(defaultIssue as relationResponse);
      }
    } catch (error) {
      console.error('初始化加载失败:', error);
    }
  });

  const selectTopItem = async (item: relationResponse) => {
    activeTop.value = item.to.id;

    try {
      const secondParams: relationByFromParams = {
        fromId: item.to.id,
        fromType: item.to.entityType,
      };
      const secondRes = await getRelationByFrom(secondParams);
      secondLayerData.value = secondRes;
      if (secondRes.length > 0) {
        activeSecond.value = secondRes[0].to.id;
        currentSecondName.value = secondRes[0].toName; // 初始化名称
      } else {
        currentSecondName.value = '';
      }
      const thirdPromises = secondRes.map(async (secondItem) => {
        const thirdParams: relationByFromParams = {
          fromId: secondItem.to.id,
          fromType: secondItem.to.entityType,
        };
        const thirdRes = await getRelationByFrom(thirdParams);
        thirdLayerData[secondItem.to.id] = thirdRes;
        await Promise.all(thirdRes.map((thirdItem) => toggleFourthLayer(thirdItem)));
      });

      await Promise.all(thirdPromises);

      if (secondRes.length > 0) {
        activeSecond.value = secondRes[0].to.id;
      }
    } catch (error) {
      console.error('加载层级数据失败:', error);
    }
  };

  const selectSecondItem = (id: string) => {
    activeSecond.value = id;

    // 根据 id 找到对应的第二层项，更新名称
    const selectedItem = secondLayerData.value.find((item) => item.to.id === id);
    if (selectedItem) {
      currentSecondName.value = selectedItem.toName;
    } else {
      currentSecondName.value = '';
    }
  };

  const toggleFourthLayer = async (item: relationResponse, forceReload = false) => {
    const itemId = item.to.id;
    // 保存当前展开状态
    const wasExpanded = activeFourth.value.includes(itemId);

    // 当强制刷新或没有缓存数据时加载
    if (forceReload || !fourthLayerData[itemId]?.length) {
      try {
        const params: relationByFromParams = {
          fromId: itemId,
          fromType: item.to.entityType,
        };
        const res = await getRelationByFrom(params);
        fourthLayerData[itemId] = res; // 使用Vue.set确保响应式更新
        // 强制刷新后恢复展开状态
        await nextTick(() => {
          if (wasExpanded || forceReload) {
            activeFourth.value = Array.from(new Set([...activeFourth.value, itemId]));
          }
        });
      } catch (error) {
        console.error('加载第四层数据失败:', error);
      }
    }
  };

  const getNodeData = async (item: relationResponse) => {
    try {
      const params: relationByFromParams = {
        fromId: item.to.id, // 根据具体需求调整参数
        fromType: item.to.entityType,
      };
      const res = await getRelationByFrom(params);
      nodeData.value = res; // 更新节点数据
      store.state.nodeData = res;
      // console.log('发送方案节点:', nodeData.value);

      const nodes = store.state.nodeData;
      // nodes.forEach((node, index) => {
      //   console.log(`节点 ${index + 1}:`, node.toName || '未命名');
      // });
    } catch (error) {
      console.error('获取节点数据失败:', error);
    }
  };

  // 上传方法
  const uploadFile = async (targetItemId?: string) => {
    const itemId = targetItemId || selectedAssetProfileId.value;
    selectedAssetProfileId.value = itemId;

    if (!itemId) {
      statusMessage.value = '未选择有效资源类别';
      return;
    }

    const fileInput = document.getElementById(`fileInput-${itemId}`) as HTMLInputElement;
    if (!fileInput?.files?.length) {
      statusMessage.value = '请先选择文件';
      return;
    }

    const file = fileInput.files[0];
    progress.value = 0;

    try {
      // 调用服务层方法（带进度回调）
      const uploadedFilename = await uploadToServer(file, (percent) => {
        progress.value = percent;
      });

      const encodedFilename = encodeURIComponent(uploadedFilename);
      const downloadUrl = `${FileLoadUrl}download/${encodedFilename}`;

      // 调用服务层保存方法
      await saveUploadData(uploadedFilename, downloadUrl, itemId);
      statusMessage.value = '文件上传并关联成功！';

      // 强制刷新当前三级菜单的数据
      const parentItem = thirdLayerData[activeSecond.value].find((item) => item.to.id === itemId);

      if (parentItem) {
        await toggleFourthLayer(parentItem, true); // 强制重新加载数据
        await nextTick();

        // 保持展开状态
        if (!activeFourth.value.includes(itemId)) {
          activeFourth.value = [...activeFourth.value, itemId];
        }
      }
    } catch (error) {
      console.error('上传失败:', error);
      statusMessage.value = `上传失败: ${(error as Error).message}`;
    } finally {
      setTimeout(() => (progress.value = 0), 2000);
    }
  };

  const { emit } = getCurrentInstance()!;

  const store = useStore();

  const selectedItemId = computed(() => store.state.selectedIssue?.to.id);

  const handleItemClick = async (fourth: relationResponse) => {
    // 直接提交 mutation
    // store.commit('SET_SELECTED_ITEM_ID', fourth.to.id);
    // store.state.selectedIssue = fourth;
    if (currentSecondName.value === '系统资源-方案') {
      store.commit('SET_SELECTED_PLAN', fourth);
      const displayName = formatName(fourth.toName);
      emit('title-change', displayName);
      store.state.selectedIssue = fourth;

      await getNodeData(fourth);

      const filenames = Object.values(nodeData).flatMap((array) =>
        array.map((item) => item.toName),
      );
      // console.log(filenames);
      console.log('选择的方案的id' + selectedItemId.value); // 通过计算属性访问

      await sendMultipleFilesToUnity(filenames);
    }
    // 新增我的资源关联逻辑
    // else if (currentSecondName.value.startsWith('我的资源-')) {
    //   try {
    //     // 增强参数校验
    //     if (!fourth?.to?.id) {
    //       ElMessage.warning('请选择有效的资源项');
    //       return;
    //     }
    //
    //     // 获取当前选中的系统方案（添加类型校验）
    //     const selectedPlan = store.state.selectedIssue as relationResponse | undefined;
    //
    //     if (!selectedPlan?.to?.id) {
    //       ElMessage.warning('请先在系统资源中选择要关联的方案');
    //       return;
    //     }
    //
    //     // 打印调试信息
    //     console.log('关联参数:', {
    //       系统方案ID: selectedPlan.to.id,
    //       资源项ID: fourth.to.id
    //     });
    //
    //     // 创建关联关系（添加请求拦截）
    //     const { data: relationRes } = await saveRelation({
    //       type: 'Contains',
    //       additionalInfo: {},
    //       typeGroup: 'COMMON',
    //       from: {
    //         entityType: 'ASSET',
    //         id: selectedPlan.to.id
    //       },
    //       to: {
    //         entityType: 'ASSET', // 根据实际情况调整
    //         id: fourth.to.id
    //       }
    //     });
    //     ElMessage.success('资产关联成功！');
    //     // 刷新视图的优化方案
    //     await Promise.all([
    //       // 刷新系统方案视图
    //       refreshSystemPlanView(selectedPlan.to.id),
    //       // 刷新当前资源视图
    //       refreshCurrentResourceView(fourth.to.id),
    //     ]);
    //
    //   } catch (error) {
    //     console.error('关联流程完整错误:', error);
    //     ElMessage.error(`关联失败: ${(error as Error).message}`);
    //   }
    // }
    else {
      if (currentSecondName.value === '结构-节点') {
        // await toggleFourthLayer(fourth);
        const filename = fourth.toName;
        chooseModel({ name: filename });
        // await sendMessageToUnity(filename);
      } else {
        await toggleFourthLayer(fourth);
        const filename = fourth.toName;
        await sendMessageToUnity(filename);
        await saveDevicePlan(filename, `${FileLoadUrl}api/upload`);
      }
    }
  };

  // 新增刷新方法
  const refreshSystemPlanView = async (planId: string) => {
    const systemSecond = secondLayerData.value.find((item) => item.toName === '系统资源-方案');

    if (systemSecond) {
      // 保持当前展开状态
      const prevExpanded = [...activeFourth.value];

      await selectTopItem(systemSecond);
      activeFourth.value = [...prevExpanded, planId];

      // 滚动到关联项
      await nextTick();
      document.querySelector(`[data-item-id="${planId}"]`)?.scrollIntoView({
        behavior: 'smooth',
        block: 'nearest',
      });
    }
  };

  const refreshCurrentResourceView = async (resourceId: string) => {
    // 查找当前资源的父级ID
    const parentItem = thirdLayerData[activeSecond.value].find((item) =>
      fourthLayerData[item.to.id]?.some((f) => f.to.id === resourceId),
    );

    if (parentItem?.to.id) {
      await toggleFourthLayer(parentItem, true);
      activeFourth.value = [...activeFourth.value, parentItem.to.id];
    }
  };

  // 数据刷新方法
  const refreshHandler = async () => {
    if (activeTop.value) {
      const topItem = topLabels.value.find((item) => item.to.id === activeTop.value);
      if (topItem) {
        await selectTopItem(topItem); // 保持原有数据加载逻辑
      }
    }
  };

  // 创建方案处理
  const handleCreatePlan = async (itemId: string) => {
    try {
      const res = await createPlan(
        itemId,
        newFolderName.value,
        activeSecond.value,
        (msg) => (folderErrorMessage.value = msg),
        (visible) => (dialogVisiblePlan.value = visible),
      );

      // 构造完整的新方案项
      const newItem: relationResponse = {
        to: {
          id: res.data.id,
          entityType: 'ASSET',
        },
        toName: `${activeSecond.value}-${newFolderName.value}`,
        from: {
          id: itemId,
          entityType: 'ASSET',
        },
        type: 'Contains',
        typeGroup: 'COMMON',
        additionalInfo: {},
      };

      // 使用响应式数组更新方法
      if (!thirdLayerData[itemId]) {
        thirdLayerData[itemId] = [];
      }
      thirdLayerData[itemId] = [newItem, ...thirdLayerData[itemId]];

      // 保持父级展开状态的关键修改
      const parentWasExpanded = activeFourth.value.includes(itemId);
      await toggleFourthLayer(
        {
          to: { id: itemId, entityType: 'ASSET' },
        },
        true,
      );

      // 恢复展开状态并添加新项
      await nextTick();
      activeFourth.value = Array.from(
        new Set([
          ...activeFourth.value,
          itemId, // 保持父级展开
          newItem.to.id, // 展开新创建项
        ]),
      );

      // 添加滚动定位
      setTimeout(() => {
        const newItemElement = document.querySelector(`[data-item-id="${newItem.to.id}"]`);
        if (newItemElement) {
          newItemElement.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        }
      }, 100);

      // 清除输入但不关闭弹窗
      newFolderName.value = '';
      // dialogVisiblePlan.value = false; // 注释掉关闭弹窗的逻辑
    } catch (error) {
      console.error('创建方案失败:', error);
      ElMessage.error('创建方案失败: ' + (error as Error).message);
    }
  };

  // 创建文件夹处理
  const handleCreateFolder = async () => {
    await createFolder(
      newFolderName.value,
      activeSecond.value,
      (msg) => (folderErrorMessage.value = msg),
      (visible) => (dialogVisibleFolder.value = visible),
      refreshHandler,
    );
    // 清理输入
    newFolderName.value = '';
  };
</script>

<style scoped>
  .container {
    background: #1e2430;
    height: 100%;
    display: flex;
    flex-direction: column;
  }

  .top-layer {
    top: 0;
    left: 0;
    width: 100%;
    z-index: 10;
    border-bottom: none;
    height: 5vh;
  }

  .top-layer li {
    margin-left: 0.4vw !important;
    width: 4vw !important;
    height: 3.4vh;
    margin-top: 0.75vh;
    background: #37434e;
    border: none;
    border-radius: 0.2vw;
    color: #617b91;
    font-size: 0.8vw;
  }

  .main-content {
    display: flex;
    width: 100% !important;
  }

  .second-layer {
    width: 3vw;
    background: #191e27;
  }

  .second-layer :hover {
    background: #111c32;
  }

  .second-layer .el-menu-item {
    width: 100%;
    height: 10vh;
    writing-mode: vertical-rl;
    text-align: center;
    white-space: nowrap;
    padding-top: 3vh;
    padding-bottom: 3vh;
    display: flex;
    font-size: 1vw;
  }

  .third-layer {
    background: #1e2430;
    width: 100%;
    margin-left: 1vw;
  }

  .scroll-container {
    height: 100%;
  }

  .third-item {
    color: white;
    width: 100%;
    text-align: left;
    font-size: 1vw;
  }

  .third-item svg {
    width: 0;
  }

  .third-content {
    background: #1e2430;
    color: white;
  }

  .fourth-layer .modal {
    overflow-y: auto;
  }

  .el-collapse {
    --el-collapse-content-bg-color: #1e2430;
    --el-collapse-header-bg-color: #1e2430;
    --el-collapse-border-color: none;
    color: white;
  }

  :deep(.el-icon) svg {
    color: #ffffff;
  }

  .graph-item {
    padding: 1vw;
    margin: 1vw 0;
    background: #37434e;
    color: #617b91;
    border-radius: 4px;
  }

  .graph-item:hover {
    background: #4583ff;
    color: #fff;
  }

  .active-top {
    background-color: #4583ff !important;
    color: #fff !important;
  }

  .search-box :deep(.el-input__wrapper) {
    margin-right: 1vw;
    margin-top: 1vh;
    box-shadow: none;
    background: #303648;
    font-size: 1vw;
    color: #fff; /* 设置文字颜色为白色 */
  }

  .search-box :deep(.el-input__inner) {
    border: none;
    caret-color: #4583ff;
    caret-width: 2px;
  }

  /* 下载文件 */
  .upload-file {
    padding-left: 1.2vw;
    height: 3vh;
    background-color: #1e2430;
    cursor: pointer;
    color: rgb(69, 131, 255); /* 默认字体颜色为蓝色 */
    font-size: 0.8vw;
    text-decoration: none; /* 默认没有下划线 */
  }

  .upload-file:hover {
    text-decoration: underline; /* 鼠标悬浮时添加下划线 */
    color: white;
  }

  .main-content {
    flex-grow: 1;
    padding: 0;
  }

  .el-menu-item.is-active {
    color: white;
  }

  /* 弹窗样式 */
  .modal,
  .plan-modal {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100%;
    justify-content: center;
    align-items: center;
    z-index: 99;
  }

  .main-content .container {
    background: white;
  }

  .close {
    position: absolute;
    right: 15px;
    top: 10px;
    cursor: pointer;
    font-size: 24px;
  }

  button {
    padding: 1vh 1vw;
    background: #2196f3;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
  }

  button:hover {
    background: #1976d2;
  }

  /* 自定义进度条样式 */
  .progress-bar {
    width: 100%;
    height: 20px;
    background-color: #f3f3f3;
    border-radius: 10px;
    overflow: hidden;
    margin-top: 10px;
  }

  .search-box :deep(.el-input__inner:focus::placeholder) {
    opacity: 0;
  }

  .progress {
    height: 100%;
    background-color: #4caf50;
    transition: width 0.3s ease; /* 平滑过渡效果 */
  }

  .fourth-layer .el-scrollbar {
    max-height: 60vh; /* 最大高度为 50vh */
    height: auto; /* 高度自适应内容 */
    overflow-y: auto;
    width: 100%;
  }

  .fourth-layer .graph-item {
    width: 12vw;
  }

  .graph-item.is-active {
    background: #4583ff !important;
    color: #fff !important;
    position: relative;
  }

  /* 系统资源-方案菜单下的特殊样式 */
  .graph-item.is-system-plan.is-active {
    background: #00c1de !important;
    box-shadow: 0 0 8px rgba(0, 193, 222, 0.5);
  }

  /* 添加选中指示条 */
  /*.graph-item.is-active::after {*/
  /*  content: '';*/
  /*  position: absolute;*/
  /*  left: 0;*/
  /*  top: 0;*/
  /*  height: 100%;*/
  /*  width: 3px;*/
  /*  background: #fff;*/
  /*}*/

  /* 添加高亮样式 */
  .highlight {
    background-color: #ffeb3b;
    color: #000;
    padding: 2px 4px;
    border-radius: 3px;
  }

  /* 调整搜索框样式 */
  .search-box {
    margin-bottom: 10px;
  }

  .search-box .el-input__inner {
    background: #2d3542 !important;
    border: 1px solid #4583ff !important;
    color: #fff !important;
  }

  .item-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
  }

  .delete-btn {
    padding: 0 5px;
    height: 20px;
    background-color: transparent !important;
    color: #ff4d4f;
    border: none;

    &:hover {
      color: #ff7875;
      transform: scale(1.1);
    }

    .el-icon {
      font-size: 14px;
    }
  }

  .item-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
  }

  .delete-file {
    padding: 0 0.5vw;
    height: 2.5vh;
    background-color: transparent !important;
    color: #ff4d4f;
    font-size: 0.7vw;
    border: none;
  }

  .delete-file:hover {
    color: #ff7875;
    text-decoration: underline;
  }

  /* 防止按钮点击触发父级点击事件 */
  .delete-file :deep(.el-button__inner) {
    pointer-events: none;
  }
</style>
